using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using ImageEffects;
using LogSystem;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class LoadGameObject : LatentActionNodeBase
    {
        public override bool allowRoutineQueueing { get { return false; } }

        private ResLoader _resLoader;
        
        private GameObject _gameObject;
        private bool _loaded = false;
        
        public IEnumerator Invoke(string resPath,string pointName)
        {
            _resLoader = ResLoader.Alloc();
            
            _resLoader.Add2Load(resPath, ((success, assetName, asset) =>
            {
                if (!success || asset == null)
                {
                    Debug.LogError(LogModule.Blueprint,$"加载资源失败：{assetName}");
                    return;
                }
                _gameObject = GameObject.Instantiate(asset as GameObject);
                var point = BlueprintUtils.GetBlueprintPoint(pointName);
                _gameObject.transform.position = point.position;
                _gameObject.transform.eulerAngles = point.eulerAngles;
                _gameObject.SetActive(true);
                _loaded = true;
            }));
            _resLoader.Load();

            while (!_loaded)
            {
                yield return new WaitForOneFrame();
            }
        }
        
        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            var p1 = node.AddValueInput<string>("resPath");
            var p2 = node.AddValueInput<string>("pointName");
            
            node.AddFlowInput("In", (f) => { Begin(Invoke(p1.value,p2.value), f); });
            
            node.AddValueOutput("npcGameObject", () => _gameObject);
        }
        
        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (_gameObject)
            {
                GameObject.DestroyImmediate(_gameObject);
            }
            
            if (_resLoader!=null)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
            }
        }
    }
}